package org.huzhp.console.entity.vo;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.huzhp.console.entity.SentinelRule;
import org.springframework.beans.BeanUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 规则类
 * @Author: huzp
 * @CreateDate: 2020/3/12 15:18
 * @Version: 1.0
 */
@Data
public class SentinelRuleVo {

    private Long id;

    private String ruleResource;

    private Integer ruleResourceMode;

    private Integer ruleGrade;

    private Double ruleCount;

    private Double ruleIntervalSec;

    private Integer ruleControlBehavior;

    private Integer ruleBurst;

    private Integer ruleMaxQueueingTimeoutMs;

    private Date create_time;

    private SentinelParamVo param;

    public SentinelRule build() {
        if (this == null) {
            return null;
        }
        SentinelRule rule = new SentinelRule();
        BeanUtils.copyProperties(this, rule);
        rule.setCreate_time(new Date());
        return rule;
    }


    public Object buildGatewayJson() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(buildGateway());
        } catch (JsonProcessingException e) {

        }
        return null;
    }

    public Object buildGateway() {
        Map<String, Object> jsonMap = new HashMap<>(9);
        jsonMap.put("resource", this.ruleResource);
        jsonMap.put("resourceMode", this.ruleResourceMode);
        jsonMap.put("grade", this.ruleGrade);
        jsonMap.put("count", this.ruleCount);
        jsonMap.put("intervalSec", this.ruleIntervalSec);
        jsonMap.put("controlBehavior", this.ruleControlBehavior);
        jsonMap.put("burst", this.ruleBurst);
        jsonMap.put("maxQueueingTimeoutMs", this.ruleMaxQueueingTimeoutMs);
        jsonMap.put("paramItem", this.param != null ? this.param.buildGatewayJson() : null);
        return jsonMap;

    }
}
